#include <jni.h>
#include "VideoChannel.h"
#include "mylog.cpp"
VideoChannel * videoChannel;
JavaVM *javaVM = 0;
JNIEnv* _env = NULL;
JavaCallHelper *javaCallHelper;
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
    jint result = -1;
    if (vm->GetEnv((void**) &_env, JNI_VERSION_1_4) != JNI_OK) {
        return -1;
    }
    javaVM = vm;
    return JNI_VERSION_1_4;
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_example_x264cameraxpush_LivePush_native_1init(JNIEnv *env, jobject thiz) {
    // TODO: implement native_init()
    videoChannel = new VideoChannel();
//    javaCallHelper = new JavaCallHelper(javaVM, env, thiz);
//    videoChannel->setJavaCallHelper(javaCallHelper);
    return 0;
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_example_x264cameraxpush_LivePush_native_1setVideoInfo(JNIEnv *env, jobject thiz,
                                                               jint width, jint height, jint fps,
                                                               jint bitrate) {
    // TODO: implement native_setVideoInfo()
    videoChannel->initVideoCodec(width,height,fps,bitrate);

    return 0;

}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_x264cameraxpush_LivePush_native_1start(JNIEnv *env, jobject thiz, jstring path) {
    // TODO: implement native_start()
    // 开始发送数据
 char * url = const_cast<char *>(env->GetStringUTFChars(path, nullptr));
    videoChannel->setRtmpUrl(url);
    videoChannel->startSendData();
    env->ReleaseStringUTFChars(path,url);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_x264cameraxpush_LivePush_native_1pushVideo(JNIEnv *env, jobject thiz,
                                                            jbyteArray data_) {
    // TODO: implement native_pushVideo()

    jbyte* data =  env->GetByteArrayElements(data_,nullptr);
    if (videoChannel) {
        videoChannel->encodeData(data);
    }
    env->ReleaseByteArrayElements(data_,data,0);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_x264cameraxpush_LivePush_native_1stop(JNIEnv *env, jobject thiz) {
    // TODO: implement native_stop()
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_x264cameraxpush_LivePush_native_1release(JNIEnv *env, jobject thiz) {
    // TODO: implement native_release()
    if (javaCallHelper) {
        delete javaCallHelper;
    }
    if (videoChannel) {
        delete videoChannel;
    }
}
